/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。
 * 
 * 欢迎到知启蒙网站（https://www.zhiqim.com）购买正版软件，知启蒙还提供许多开源框架和软件。
 * 
 * 1、本软件产品所有源代码受《中华人民共和国著作权法》和其他有关法律、法规的保护，其所有知识产权归湖南知启蒙科技有限公司所有；
 * 2、禁止复制和修改。不得复制修改、翻译或改编本软件所有源代码，或者基于本软件产品创作衍生作品；
 * 3、禁止进行逆向工程。不得对本软件的源代码进行逆向工程、反编译或试图以其他方式发现软件的源代码；
 * 4、个别授权：如需进行商业性的销售、复制、分发，包括但不限于软件销售、预装、捆绑等，必须获得知启蒙的书面授权和许可；
 * 5、保留权利：本注释未明示授权的其他一切权利仍归知启蒙所有，任何人使用其他权利时必须获得知启蒙的书面同意。
*/
package net.redxyz.repost.service.handler;

import org.zhiqim.kernel.Global;
import org.zhiqim.kernel.control.Handler;
import org.zhiqim.kernel.logging.Log;
import org.zhiqim.kernel.logging.LogFactory;
import org.zhiqim.kernel.util.DateTimes;
import org.zhiqim.orm.ORM;
import org.zhiqim.orm.dbo.Updater;

import net.redxyz.repost.resource.model.AssRepostModel;
import net.redxyz.repost.service.task.repost.RepostPlanTask;
import net.redxyz.top.TaobaoService;
import net.redxyz.top.data.item.Item;
import net.redxyz.top.message.item.AlibabaItemOperateDownshelfResponse;
import net.redxyz.top.message.item.AlibabaItemOperateUpshelfResponse;
import net.redxyz.top.message.item.ItemSellerGetResponse4_24625;
import net.redxyz.top.repost.dbo.AssRepostPlanDetail;
import net.redxyz.top.repost.dbo.AssRepostPlanLog;

/**
 * 均衡调整计划每分钟检查上下架处理器
 *
 * @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
 */
public class RepostHandler implements Handler<AssRepostModel>
{
    private static final Log log = LogFactory.getLog("timer.repost.log");

    public void process(AssRepostModel dto)
    {
        String operateTime = DateTimes.getDateTimeString();

        String nick = dto.getNick();
        String planId = dto.getPlanId();
        long numIid = dto.getNumIid();
        boolean isDelay = dto.isDelay();

        String sessionId = dto.getSessionId();
        String email = dto.getEmail();

        String itemTitle = dto.getItemTitle();
        String itemPicUrl = dto.getItemPicUrl();
        int itemNum = dto.getItemNum();
        String id = planId + "_" + numIid;

        try
        {
            ItemSellerGetResponse4_24625 resp0 = TaobaoService.getItemService().getItem(nick, sessionId, numIid);
            if(resp0.isTaobaoFail())
                resp0 = TaobaoService.getItemService().getItem(nick, sessionId, numIid);
            
            if (!resp0.isSuccess())
            {
                updatePlanDetail(nick, planId, numIid, 3, 3, operateTime, "宝贝查询失败[" + resp0.toString() + "]");
                log.error("用户[" + nick + "]宝贝[" + numIid + "]查询失败:" + resp0.getErrorMsg());
                return;
            }

            Item item = resp0.getItem();
            if (!isDelay && !item.isOnsale())
            {// 不在出售中
                updatePlanDetail(nick, planId, numIid, 3, 3, operateTime, "宝贝不在出售中，不再调整");
                log.error("用户[" + nick + "]宝贝[" + numIid + "]不在出售中");
                return;
            }

            // 先下架
            AlibabaItemOperateDownshelfResponse resp1 = TaobaoService.getItemService().itemDownshelf(nick, sessionId, numIid);
            if (!resp1.isSuccess())
            {
                if (resp1.isTaobaoFail())
                {
                    Thread.sleep(1000);
                    resp1 = TaobaoService.getItemService().itemDownshelf(nick, sessionId, numIid);
                }

                if (resp1.isTaobaoFail())
                {
                    Thread.sleep(2000);
                    resp1 = TaobaoService.getItemService().itemDownshelf(nick, sessionId, numIid);
                }

                if (!resp1.isSuccess())
                {
                    if(resp1.isTaobaoFail())
                    {//调整失败顺延到下一分钟处理
                        log.info("均衡上架[" + nick + "]先下架[" + numIid + "]失败[" + resp1.getErrorMsg() + "]，顺延到下一分钟处理");
                        doHandlerNextMin(planId, numIid, operateTime);
                    }
                    else
                    {
                        log.error("均衡上架[" + nick + "]先下架[" + numIid + "]失败[" + resp1.getErrorMsg() + "]");
                        updatePlanDetail(nick, planId, numIid, 0, 2, operateTime, "宝贝下架时操作失败[" + resp1.toString() + "]");
                        insertPlanLog(nick, email, planId, numIid, itemTitle, itemPicUrl, itemNum, operateTime, "下架宝贝失败：" + resp1.getErrorMsg());
                    }
                    
                    return;
                }
            }

            log.info("均衡上架[" + nick + "]先下架[" + numIid + "]成功");

            // 睡眠1秒后上架
            Thread.sleep(1000);
            AlibabaItemOperateUpshelfResponse resp2 = TaobaoService.getItemService().itemUpshelf(nick, sessionId, numIid, item.getNum());
            if (!resp2.isSuccess())
            {
                if (resp2.isTaobaoFail())
                {
                    Thread.sleep(1000);
                    resp2 = TaobaoService.getItemService().itemUpshelf(nick, sessionId, numIid, item.getNum());
                }

                if (resp2.isTaobaoFail())
                {
                    Thread.sleep(2000);
                    resp2 = TaobaoService.getItemService().itemUpshelf(nick, sessionId, numIid, item.getNum());
                }

                if (!resp2.isSuccess())
                {
                    if(resp2.isTaobaoFail())
                    {//调整失败顺延到下一分钟处理
                        log.info("均衡上架[" + nick + "]后上架[" + numIid + "]失败[" + resp2.getErrorMsg() + "]，顺延到下一分钟处理");
                        doHandlerNextMin(planId, numIid, operateTime);
                    }
                    else
                    {
                        log.error("均衡上架[" + nick + "]后上架[" + numIid + "]失败[" + resp2.getErrorMsg() + "]");
                        updatePlanDetail(nick, planId, numIid, 0, 2, operateTime, "宝贝上架时操作失败[" + resp2.toString() + "]");
                        insertPlanLog(nick, email, planId, numIid, itemTitle, itemPicUrl, itemNum, operateTime, "上架宝贝失败：" + resp2.getErrorMsg());
                    }
                    
                    return;
                }
            }
            
            log.info("均衡上架[" + nick + "]后上架[" + numIid + "]成功");
            String updateTime = DateTimes.getDateTimeString();
            updatePlanDetail(nick, planId, numIid, 0, 1, updateTime, "宝贝调整成功[" + updateTime + "]");
        }
        catch (Exception e)
        {
            e.printStackTrace();
            log.error("用户[" + nick + "]宝贝[" + numIid + "]自动上下架调整失败");
        }
        finally
        {
            Global.get(RepostPlanTask.class).remove(id);
        }
    }

    private void updatePlanDetail(String nick, String planId, long numIid, int itemStatus, int operateStatus,
        String operateTime, String operateDetail)
    {
        Updater updater = new Updater();
        updater.addMaybe("planId", planId);
        updater.addMaybe("numIid", numIid);
        updater.addField("itemStatus", itemStatus);
        updater.addField("operateStatus", operateStatus);
        updater.addField("operateTime", operateTime);
        updater.addField("operateDetail", operateDetail);
        updater.addReplace("d", "001");

        try
        {
            ORM.table().update(AssRepostPlanDetail.class, updater);
        }
        catch (Exception e)
        {
            log.error("均衡上架[" + nick + "]宝贝[" + numIid + "]更新状态异常", e);
        }
    }

    /**
     * 增加错误日志
     *
     * @param nick
     * @param email
     * @param planId
     * @param numIid
     * @param itemTitle
     * @param itemPicUrl
     * @param itemNum
     * @param operateTime
     * @param operateDesc
     */
    private void insertPlanLog(String nick, String email, String planId, long numIid, String itemTitle, String itemPicUrl, int itemNum,
        String operateTime, String operateDesc)
    {
        // 增加均衡调整错误日志
        AssRepostPlanLog planLog = new AssRepostPlanLog();
        planLog.setNick(nick);
        planLog.setNumIid(numIid);
        planLog.setItemNum(itemNum);
        planLog.setPlanId(planId);
        planLog.setItemPicUrl(itemPicUrl);
        planLog.setItemTitle(itemTitle);
        planLog.setOperateDesc(operateDesc);
        planLog.setOperateTime(operateTime);

        try
        {
            ORM.table().replace(planLog);
        }
        catch (Exception e)
        {
            log.error("均衡调整[" + nick + "]宝贝[" + numIid + "]插入错误日志异常", e);
        }
    }
    
    /**
     * 下一分钟处理
     * 
     * @param planId
     * @param numIid
     * @param operateTime 2018-06-22 17:03:27
     * 
     * @throws Exception
     */
    private static void doHandlerNextMin(String planId, long numIid, String operateTime) throws Exception
    {
        Updater updater = new Updater();
        updater.addMaybe("planId", planId);
        updater.addMaybe("numIid", numIid);
        updater.addField("operateTime", operateTime);
        updater.addField("operateDetail", "宝贝调整失败，顺延到下一分钟处理");
        updater.addField("itemStatus", 4);//标识下延迟调整
        updater.addReplace("d", "001");

        ORM.table().update(AssRepostPlanDetail.class, updater);
    }

}
